package ReentrantReadWriteLock_4;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class SharedData {
    private int data = 0;
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void readData() {
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 读取数据: " + data);
            Thread.sleep(20); // 模拟读取时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public void writeData(int newValue) {
        rwLock.writeLock().lock();
        try {
            data = newValue;
            System.out.println(Thread.currentThread().getName() + " 写入数据: " + data);
            Thread.sleep(50); // 模拟写入时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.writeLock().unlock();
        }
    }
}

public class 基本读写锁使用_共享数据访问 {
    public static void main(String[] args) {
        final SharedData sharedData = new SharedData();

        // 创建30个读取线程
        for (int i = 0; i < 30; i++) {
            new Thread(new Runnable() {
                public void run() {
                    sharedData.readData();
                }
            }, "读取线程-" + i).start();
        }

        // 创建10个写入线程
        for (int i = 0; i < 10; i++) {
            final int value = i;
            new Thread(new Runnable() {
                public void run() {
                    sharedData.writeData(value);
                }
            }, "写入线程-" + i).start();
        }
    }
}